<template>
  <el-dialog :title="title" :visible.sync="openx" width="800px" append-to-body :before-close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="demo-ruleForm">
      <el-form-item label="商品和包装" prop="entrust_company">
        <el-select v-model="form.goods_name" filterable placeholder="商品" clearable style="width: 50%" @change="getPacking(1)">
          <el-option
            v-for="(item,index) in selectPro"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="form.packing_id" filterable placeholder="包装" clearable style="width: 50%" @change="ck_info">
          <el-option
            v-for="(item,index) in selectPick"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="config_name">
        <span slot="label">
          库位号
        </span>
        <el-input v-model="form.config_name" type="text" style="width: 50%"/>
        <span style="margin-left: 5%;">总数：{{total_num}} / 总箱数：{{total_box}}</span>
      </el-form-item>
      <el-form-item prop="batch_number">
        <span slot="label">
          批次号
        </span>
        <el-input v-model="form.batch_number" type="text" style="width: 50%"/>
        <el-button type="success" size="medium" @click="getTray" style="margin-left: 5%;">获取托盘</el-button>
      </el-form-item>
      <el-form-item>
        <span slot="label">
          托盘
        </span>
        <el-select v-model="form.stock_ids" multiple filterable placeholder="托盘码" clearable style="width: 100%">
          <el-option
            v-for="(item,index) in selectTray"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
        <el-col :span="24">
          <el-button type="primary" size="medium" @click="submitForm('form')">{{ title }}</el-button>
          <el-button size="medium" @click="close()">取消</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { createWarehouseOutSon, updateWarehouseOutSon, delWarehouseOutSon,fastOut } from '@/api/storehouse'
import { getGPSelect,getGoods,getPacking } from '@/api/product'
import { pickFast} from '@/api/stock'
export default {
  name: 'Fast',
  props: {
    openx: {
      type: Boolean
    },
    form: {
      type: Object
    },
    title: {
      type: String
    },
    warehouseoutid: {
      type: String
    }
  },
  data() {
    return {
      rules: {
        // goods_name: [
        //   { required: true, message: '请选择商品', trigger: 'blur' }
        // ],
        // packing_id: [
        //   { required: true, message: '请选择包装', trigger: 'blur' }
        // ]
      },
      selectData: [],
      selectPro:[],
      selectPick:[],
      selectTray:[],
      num: 0,
      isLoad: true,
      packing_id: '',
    }
  },
  computed:{
    total_num(){
      var total = 0
      if(this.form.stock_ids){
        this.selectTray.forEach((item)=>{
          if(this.form.stock_ids.includes(item.stock_id)){
            total += item.Good_Qty
          }
        })
      }
      return total
    },
    total_box(){
      var total = 0
      if(this.form.stock_ids){
        this.selectTray.forEach((item)=>{
          if(this.form.stock_ids.includes(item.stock_id)){
            total += item.box_number
          }
        })
      }
      return total
    }
  },
  watch: {
    'form.number': {
      deep: true,
      handler(val) {
        this.ck_num()
      }
    },
    title:{
      handler(val) {
        if(val == '编辑'){
          this.getPacking(2)
        }
      }
    }
  },
  created() {
    //this.getGoods()
  },
  methods: {
    /** 获取托盘 **/
    getTray(){
      const that = this
      if(!that.form.goods_name){
        that.$message.warning('未选择商品')
        return false
      }
      if(!that.form.packing_id){
        that.$message.warning('未选择包装')
        return false
      }
      // if(!that.form.config_name){
      //   that.$message.warning('缺少库位号')
      //   return false
      // }
      // if(!that.form.batch_number){
      //   that.$message.warning('缺少批次号')
      //   return false
      // }
      pickFast({warehouse_out_id:that.warehouseoutid,goods_name:that.form.goods_name,packing_id:that.form.packing_id,config_name:that.form.config_name,batch_number:that.form.batch_number}).then(response => {
        if (response.code === 10000) {
          console.log(response.data)
          that.selectTray = JSON.parse(JSON.stringify(response.data))
          that.selectTray.forEach((item)=>{
            item.label = '库位: '+item.config_name+' / 托盘: '+item.tray_id+' / 数量: '+item.Good_Qty
            item.value = item.stock_id
          })
        }
      })
    },
    ck_num(){
      if(!this.form.number){
        return false
      }
      if(!this.form.packing_id){
        return false
      }
      if(this.selectPick.length == 0){
        return false
      }
      var packing_num = 0
      var data = JSON.parse(JSON.stringify(this.selectPick))
      data.forEach((item)=>{
        if(item.value == this.form.packing_id){
          packing_num = item.packing_num
        }
      })
      this.form.box_number = Math.ceil(parseInt(this.form.number) / parseInt(packing_num))
    },
    ck_info(){
      if(!this.form.number){
        return false
      }
      if(this.selectPick.length == 0){
        return false
      }
      var packing_num = 0
      var data = JSON.parse(JSON.stringify(this.selectPick))
      data.forEach((item)=>{
        if(item.value == this.form.packing_id){
          packing_num = item.packing_num
        }
      })
      this.form.box_number = Math.ceil(parseInt(this.form.number) / parseInt(packing_num))
    },
    /** 初始：查询商品 */
    getGoods() {
      const that = this
      this.isLoad =true
      getGoods().then(response => {
        if (response.code === 10000) {
          that.selectPro = JSON.parse(JSON.stringify(response.data))
          that.selectPro.forEach((item)=>{
            item.label = item.goods_name
            item.value = item.goods_name
            this.isLoad =false
          })
        }
      })
    },
    /** 动态获取商品规格 */
    getPacking(type){
      if(type == 1){
        delete(this.form.packing_id)
      }
      const that = this
      getPacking({goods_name:this.form.goods_name}).then(response => {
        if (response.code === 10000) {
          var data = JSON.parse(JSON.stringify(response.data))
          data.forEach((item)=>{
            item.label = item.label
            //item.value = item.packing_id
            item.value = item.packing_id
            //item.num = item.packing_num
          })
          this.selectPick = data
        }
      })
    },
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (that.title === '快速出库') {
            this.add()
          }
        } else {
          return false
        }
      })
    },
    getProductpPcking() {
      const that = this
      getGPSelect().then(response => {
        if (response.code === 10000) {
          this.selectData = JSON.parse(JSON.stringify(response.data))
          that.selectList(this.selectData)
        }
      })
    },
    // 箱子改变
    box_number_change() {
      // eslint-disable-next-line use-isnan
      if (Number(this.form.number) !== NaN && Number(this.form.number) > 0 && this.form.packing_id && this.form.packing_id.length === 2) {
        // eslint-disable-next-line no-unused-vars
        var num = 0
        // console.log(JSON.stringify(this.selectData))
        for (var i = 0; i < this.selectData.length; i++) {
          if (this.form.packing_id[0].toString() === this.selectData[i].value.toString()) {
            for (var n = 0; n < this.selectData[i].children.length; n++) {
              // console.log(this.form.packing_id[1], this.selectData[i].children[n].value)
              if (this.form.packing_id[1].toString() === this.selectData[i].children[n].value.toString()) {
                num = this.selectData[i].children[n].num

                break
              }
            }
            break
          }
        }
        // console.log('eeeeee', Number(this.form.number), num, Number(this.form.number) / num)
        this.form.box_number = Math.ceil(Number(this.form.number) / num)
      } else {
        this.form.box_number = undefined
      }
    },
    add() {
      const that = this
      const info = {
        warehouse_out_id: this.warehouseoutid,
        goods_name:this.form.goods_name,
        packing_id:this.form.packing_id,
        stock_ids: this.form.stock_ids,
        total_num: this.total_num,
        total_box:this.total_box
      }
      if(!info.goods_name){
        that.$message.warning('请选择商品')
        return false
      }
      if(!info.packing_id){
        that.$message.warning('请选择包装')
        return false
      }
      if(!info.stock_ids.length){
        that.$message.warning('未选择托盘')
        return false
      }
      fastOut(info).then(response => {
        if (response.code === 10000) {
          that.$message.success(response.message)
          that.$parent.getList()
          that.$emit('update:openx', false)
        }
      })
    },
    edit() {
      const that = this
      const info = {
        id: this.form.id,
        warehouse_out_id: this.warehouseoutid,
        packing_id: [this.form.goods_name,this.form.packing_id],
        number: this.form.number,
        box_number: this.form.box_number
      }
      updateWarehouseOutSon(info).then(response => {
        if (response.code === 10000) {
          that.$message.success(response.message)
          that.$parent.getList()
          that.$emit('update:open', false)
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    close() {
      this.$emit('update:openx', false)
    },
    /* 处理数据 */
    selectList(data) {
      const replaceKey = function(data) {
        data.forEach(function(row, index, arr) {
          if (row.children !== undefined) {
            const temp = { label: row.goods_name, value: row.goods_id }
            if (row.children.length > 0) {
              temp['children'] = []
              row.children.forEach(item => {
                const info = {
                  label: '包装数量(' + item.packing_num + ')--包装单位(' + item.unit_name + ')',
                  value: item.packing_id,
                  num: item.packing_num
                }
                temp['children'].push(info)
              })
            }
            arr[index] = temp
            if (arr[index].children && arr[index].children.length > 0) {
              replaceKey(arr[index].children)
            }
          }
        })
      }
      replaceKey(data)
      this.isLoad =false
    }
  }
}
</script>
